package com.cool4j.generator.builder

import com.cool4j.generator.entity.Table
import com.cool4j.generator.exception.ExceptionMessage
import com.cool4j.generator.util.GeneratorUtil
import com.cool4j.generator.util.LogUtil
import com.cool4j.view.entity.HandlerVO
import freemarker.template.Configuration
import freemarker.template.TemplateException

/**
 * Service 和 DAO 构造器类
 *
 * @author Frank create on 16/1/8 14:54
 */
class ServiceBuilder extends BaseBuilder {

    @Override
    boolean builder(Table table, String packagePath, HandlerVO handlerVO, Configuration config) {
        def tableData = getDataMap(table, packagePath, handlerVO)
        def outputPath = handlerVO.getOutputPath()
        try {
            createClass(table, config, tableData, "Service", "service", "Service.ftl", outputPath)
            createClass(table, config, tableData, "ServiceImpl", "service/impl", "ServiceImpl.ftl", outputPath)
            createClass(table, config, tableData, "Dao", "dao", "Dao.ftl", outputPath)
            createClass(table, config, tableData, "DaoImpl", "dap/impl", "DaoImpl.ftl", outputPath)
        } catch (IOException e) {
            LogUtil.logging(ExceptionMessage.LOG_SERVICE_BUILDER_IO_EXCEPTION, e)
            return false
        } catch (TemplateException e) {
            LogUtil.logging(ExceptionMessage.LOG_SERVICE_BUILDER_TEMPLATE_EXCEPTION, e)
            return false
        } catch (Exception e) {
            LogUtil.logging(ExceptionMessage.LOG_SERVICE_BUILDER_OTHER_EXCEPTION, e)
            return false
        }
        return true
    }

    private void createClass(table, config, tableData, classSuffix, packageName, tempName,
                             outputPath) throws IOException, TemplateException {
        /** 获取或创建一个模板 */
        def template = config.getTemplate(tempName, "UTF-8")
        def filePath = outputPath + "/" + packageName + "/" + table.getClassName() + classSuffix + ".java"
        GeneratorUtil.writeFile(filePath, template, tableData)
    }
}
